package com.mediacloud.app.newsmodule.activity.video

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.chinamcloud.audioserver.APSLifecycleKit
import com.eventTrack.CDPTrackReportManager
import com.eventTrack.TXReportManager
import com.luck.picture.lib.tools.DoubleUtils
import com.mediacloud.app.model.fragment.BaseFragment
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.VideoLiveDetailActivity
import com.mediacloud.app.newsmodule.activity.VideoVodDetailActivity
import com.mediacloud.app.newsmodule.activity.audio.IScrollView
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.newsmodule.utils.*
import com.mediacloud.app.quanzi.model.BaseDataListBean
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import com.tencent.liteav.demo.superplayer.model.entity.VideoAlbumNew
import com.tencent.mmkv.MMKV
import kotlinx.android.synthetic.main.audio_album_program_layout.recyclerView
import kotlinx.android.synthetic.main.audio_album_program_layout.refreshLayout
import kotlinx.android.synthetic.main.refresh_recyclerview_layout.*
import kotlinx.android.synthetic.main.video_album_program_layout.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class VideoAlbumListFragment : BaseFragment(), IScrollView, OnRefreshListener, Runnable {
    var adapter: VideoAlbumProgramAdapter = VideoAlbumProgramAdapter()

    var orderDir = "desc"//desc-倒序。asc-正序默认倒序
    var activity: VideoAlbumDetailActivity? = null
    var smoothScroller: TopSmoothScroller? = null
    override fun getLayoutResID(): Int {
        return R.layout.video_album_program_layout
    }

    private var albumId: String? = null

    override fun initView() {
        albumId = arguments?.getString("AlbumId")

        getDataList(albumId)
        refreshLayout.setEnableLoadMore(false)
        refreshLayout.setEnableRefresh(true)
        refreshLayout.setOnRefreshListener(this)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        recyclerView.adapter = adapter
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        commonExpose()
                    }
                }
            }
        })
        (recyclerView.getItemAnimator() as SimpleItemAnimator).setSupportsChangeAnimations(false)

        activity = requireActivity() as VideoAlbumDetailActivity

        adapter.setOnItemClickListener { adapter, _, position ->
            if (DoubleUtils.isFastDoubleClick()) {
                return@setOnItemClickListener
            }
            val item = adapter.getItem(position) as VideoAlbumNew
            val intent = Intent(requireContext(), VideoVodDetailActivity::class.java)
            val b = Bundle()
            val articleItem = ArticleItem()
            articleItem.id = item.id.toLong()
            articleItem.title = item.title
            articleItem.logo=item.logo
            articleItem.publishDate = item.publishDate
            articleItem.publishdate = item.publishDate
            if (TXReportManager.getInstance().firstTabInfo.tabName == "视听") {
                CDPTrackReportManager.getInstance()
                    .ShortVideoClick( articleItem,position)
            }
            b.putString("articleId", "${item.albumId}")
            b.putParcelable("data",articleItem)
            MMKV.defaultMMKV().encode("current_episode",position+1)
            MMKV.defaultMMKV().encode("program_episode",adapter.data.size)
            intent.putExtras(b)
            FacadeInvoker.getFacadeData(requireContext(),item.id)
            startActivity(intent)
        }

        smoothScroller = TopSmoothScroller(requireContext())
        BindEventBus(this, adapter)

        order.setOnClickListener {
            if (order.text.contains("正序")){
                order.text = "倒序"
                order.setCompoundDrawablesWithIntrinsicBounds(null,null,
                    ContextCompat.getDrawable(it.context,R.drawable.icon_album_desc),null)
                orderDir = "desc"
            }else{
                order.text = "正序"
                order.setCompoundDrawablesWithIntrinsicBounds(null,null,
                    ContextCompat.getDrawable(it.context,R.drawable.icon_album_asc),null)
                orderDir = "asc"
            }
            getDataList(albumId)
        }
    }

    var needSendTx = false
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && needSendTx) {
            commonExpose()
            needSendTx = false
        }
    }

    var mTotalRecords: Int? = null
    var firstPageSize = 100
    private fun getDataList(albumId: String?) {

        mTotalRecords = null
        SpiderCmsApi.getSpiderCmsApi(requireContext())
            .findFirstChildArticlePage(albumId, 1, firstPageSize,orderDir,"publishDate")
            .enqueue(object : Callback<BaseDataListBean<VideoAlbumNew>> {
                override fun onResponse(
                    call: Call<BaseDataListBean<VideoAlbumNew>>,
                    response: Response<BaseDataListBean<VideoAlbumNew>>
                ) {
                    if (getActivity() == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout.finishRefresh()
                    if (response.isSuccessful){
                        response.body()?.data?.let{
                            adapter.setNewData(it.pageRecords)
                            videoSum.text = "共${it.pageRecords.size}集"
                        }
                    }
                }

                override fun onFailure(call: Call<BaseDataListBean<VideoAlbumNew>>, t: Throwable) {

                }
            })


    }


    fun backgroundAlpha(bgAlpha: Float) {
        val lp: WindowManager.LayoutParams = requireActivity().window.attributes
        lp.alpha = bgAlpha
        requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        requireActivity().window.setAttributes(lp)
    }




    override fun getScrollView(): View {
        return recyclerView
    }



    override fun onRefresh(refreshLayout: RefreshLayout) {
        getDataList(albumId)
    }


    override fun run() {
        recyclerView?.let {
            try {
                val manager = recyclerView.layoutManager as LinearLayoutManager
                val firstPosition = manager.findFirstVisibleItemPosition()
                val lastPosition = manager.findLastVisibleItemPosition()
                if (lastPosition < 0 || firstPosition < 0) {
                    return
                }
                for (i in firstPosition until lastPosition + 1) {
                    val bean = adapter.data[i]

                }
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }

        }
    }

    /**
     * 曝光通用延迟
     */
    private fun commonExpose() {
        recyclerView.removeCallbacks(this@VideoAlbumListFragment)
        recyclerView.postDelayed(this@VideoAlbumListFragment, TXReportManager.EXPOSURE_DELAY)
    }
}